// pages/questions/questions.js
const util = require('../../utils/util.js');
const wxPromisify = util.wxPromisify;
const wx_request_promisify = wxPromisify(wx.request);
let prefix = 'https://lxr.tunnel.qydev.com';
var wxCharts = require('../../utils/wxcharts.js');
var pieChart = null;
let session_id = wx.getStorageSync('JSESSIONID');//本地取存储的sessionID
var app = getApp();
Page({
  data: {
    items: [],
    activeItem: 0,
    btnPre: false,
    btnNext: false,
    seleted: [],//已答题集合
    switchResult: false,
    instanceItemInfo: {},
    showModalStatus: false//默认隐藏问卷列表

  },
  onLoad: function (options) {
    var _this = this;
    var _instanceItemId = options.instanceItemId || "";//互动项ID
    _this.setData({
      switchResult: options.switchResult || false
    });
    _this.setData({
      instanceItemId: options.instanceItemId
    });
    /* 试题列表 */
    // ../../user/interact/findInstanceItemById.json
    wx_request_promisify({
      url: prefix + '/6ds/findInstanceItemById.json',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8', 'Cookie': 'JSESSIONID=' + session_id
      },
      method: 'POST',
      data: {
        instanceItemId: _instanceItemId
      }
    }).then(res => {
      _this.setData({
        instanceItemInfo: res.data.data.instanceItem
      });
      _this.setData({
        interactionType: _this.data.instanceItemInfo.itemType
      });
      _this.setData({
        interactionState: _this.data.instanceItemInfo.itemState
      });
      return res.data.data;
    }).then((data) => {
      //'../../user/interact/' + url + '.json?instanceItemId=' + instanceItemId
      let url = _this.data.switchResult ? 'findUserQuestionResult' : 'findQuestionList';
      wx_request_promisify({
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8', 'Cookie': 'JSESSIONID=' + session_id
        },
        url: prefix + '/6ds/' + url + '.json?instanceItemId=' + _instanceItemId,
        emulateJSON: true
      }).then((res) => {
        if (!res.data.success) return;
        let item = _this.data.switchResult ? res.data.data.questionList : res.data.data;
        if (item.length > 0) {
          _this.setData({
            items: item
          });
          _this.refeshBtn();
          if (_this.data.switchResult && _this.data.interactionState === 3 && _this.data.interactionType != 3) {
            let pie_data = [];
            item[_this.data.activeItem].optionList.forEach((item) => {
              pie_data.push({
                data: item.answerPerson,
                name: item.answerCode
              });
            })
            this.initPie(pie_data);
          }
        } else {
          wx.showToast({
            title: '还未配置试题',
            image: '../../images/icon-no.png',
            duration: 2000
          });
        }
      })
      return data;
    })
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  initPie: function (data) {
    //初始化饼图
    // [{
    //   name: '成交量1',
    //   data: 15,
    // }]
    pieChart = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas',
      type: 'pie',
      series: data,
      width: 375,
      height: 300,
      dataLabel: true
    });
  },
  optionactive: function (event) {
    //试题点击事件
    var that = this;
    if (!(that.data.switchResult && that.data.interactionState === 3 && that.data.interactionType != 3)) {
      var _data = event.target.dataset;
      var items = this.data.items;
      for (var i = 0; i < items.length; i++) {
        if (_data.instancequestionid == items[i].instanceQuestionId) {
          var _optionList = items[i].optionList;
          for (var j = 0; j < _optionList.length; j++) {
            if (_data.questiontype == 1) {//单选题点击
              if (_data.instanceoptionid == _optionList[j].instanceOptionId && _optionList[j].changeColor == false) {
                _optionList[j].changeColor = true;
              } else {
                _optionList[j].changeColor = false;
              }
            } else if (_data.questiontype == 2) {//多选题
              if (_data.instanceoptionid == _optionList[j].instanceOptionId) {
                _optionList[j].changeColor = _optionList[j].changeColor == false ? true : false;
              }
            }
          }
        }
      }
      this.setData({
        items: items
      });
      this.selectedQ();
    }

  },
  refeshBtn: function () {
    // 页面初始化 options为页面跳转所带来的参数
    if (this.data.items.length > 1 && this.data.activeItem < (this.data.items.length - 1)) {
      this.setData({
        btnNext: true
      })
    } else {
      this.setData({
        btnNext: false
      })
    }
    if (this.data.activeItem > 0) {
      this.setData({
        btnPre: true
      })
    } else {
      this.setData({
        btnPre: false
      })
    }
  },
  btnNext: function () {
    //下一题
    var nextQ = this.data.activeItem + 1;
    this.setData({
      activeItem: nextQ
    })
    this.refeshBtn();
    this.selectedQ();
  },
  btnPre: function () {
    //上一题
    var nextQ = this.data.activeItem - 1;
    this.setData({
      activeItem: nextQ
    })
    this.refeshBtn();
    this.selectedQ();
  },
  selectedQ: function () {
    //已选试题
    var that = this;
    var items = this.data.items;
    var _selected = [];
    for (var i = 0; i < items.length; i++) {
      var _optionList = items[i].optionList;
      var _m = [];//多选题
      for (var j = 0; j < _optionList.length; j++) {
        if (items[i].questionType == 1) {//单选题点击
          if (_optionList[j].changeColor == true) {
            _selected.push({
              "personAnswer": _optionList[j].answerCode,
              "instanceQuestionId": _optionList[j].instanceQuestionId
            })
          }
        } else if (items[i].questionType == 2) {//多选题
          if (_optionList[j].changeColor == true) {
            _m.push(_optionList[j].answerCode)
          }
        }
      }
      if (items[i].questionType == 2 && _m.length > 0) {//多选题
        _selected.push({
          "personAnswer": _m.join(","),
          "instanceQuestionId": items[i].instanceQuestionId
        })
      }
    }
    this.setData({
      seleted: _selected
    })
  },
  btnCommit: function () {
    var _this = this;
    //提交试卷../../user/interact/findInstanceItemById.json
    var _instanceItemId = this.data._instanceItemId;
    wx_request_promisify({
      url: prefix + '/6ds/findInstanceItemById.json',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8', 'Cookie': 'JSESSIONID=' + session_id
      },
      method: 'POST',
      data: {
        instanceItemId: _instanceItemId
      }
    }).then((res) => {
      if (res.data.data.instanceItem && res.data.data.instanceItem.itemState === 3) {
        wx.showToast({
          title: '问卷已经结束',
          image: '../../images/icon-no.png',
          duration: 2000
        });
        return true
      }
    }).then((type) => {
      if (type) return;
      var str = _this.data.seleted.join();
      // ../../user/interact/submitPaper.json
      this.$http.post(prefix + '/6ds/submitPaper.json', {
        instanceItemId: _instanceItemId,
        answerStr: str
      }, { emulateJSON: true })
        .then((res) => {
          if (!res.data.success) return;
          wx.showToast({
            title: '请跳转提交成功界面',
            image: '../../images/icon-no.png',
            duration: 2000
          });
        })
    })
  }, showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  btnViewList: function () {
    this.showModal();
  }
})